package com.glink.manage.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.glink.common.exception.GeneralSimpleException;
import com.glink.common.util.BaseCommonUtils;
import com.glink.manage.common.Constants;
import com.glink.manage.domain.ConstructionWorkSiteBean;
import com.glink.manage.domain.HomeSetBean;
import com.glink.manage.domain.PatrolIntelligentEquip;
import com.glink.manage.domain.PatrolIntelligentEquipChannel;
import com.glink.manage.dto.view.HomeInfoGetInfoDTO;
import com.glink.manage.dto.view.HomeSetInfoDTO;
import com.glink.manage.dto.view.PatrolIntelligentEquipChannelHomeDTO;
import com.glink.manage.mapper.HomeSetMapper;
import com.glink.manage.service.ConstructionWorkSiteService;
import com.glink.manage.service.HomeSetService;
import com.glink.manage.service.PatrolIntelligentEquipChannelService;
import com.glink.manage.service.PatrolIntelligentEquipService;
import com.glink.manage.vo.overview.HomeSetInfoVO;
import com.glink.manage.vo.video.PatrolIntelligentEquipChannelNvrVO;
import com.glink.manage.vo.video.PatrolIntelligentEquipTreeVO;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class HomeSetServiceImpl extends ServiceImpl<HomeSetMapper, HomeSetBean> implements HomeSetService {

    @Autowired
    private ConstructionWorkSiteService constructionWorkSiteService;

    @Autowired
    private PatrolIntelligentEquipChannelService patrolIntelligentEquipChannelService;

    @Autowired
    private PatrolIntelligentEquipService patrolIntelligentEquipService;

    @Override
    @Transactional(value = "transactionManager", propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public boolean insertHomeSet(HomeSetInfoDTO dto)throws GeneralSimpleException {
        String channelObjIdStr = "";
        if(CollectionUtils.isNotEmpty(dto.getChannelObjId())){
            channelObjIdStr = String.join(",", dto.getChannelObjId());
        }
        
        HomeSetBean homeSetBean = this.lambdaQuery().eq(HomeSetBean::getConstructionWorkSiteId, dto.getConstructionWorkSiteId()).orderByDesc(HomeSetBean::getCreateTime).last(Constants.LAST_SQL).one();
        if(Objects.nonNull(homeSetBean)){
            homeSetBean.setChannelObjId(channelObjIdStr);
            homeSetBean.setPlayWindowNum(dto.getPlayWindowNum());
            homeSetBean.setDefaultSetting(1);
        }else{
            homeSetBean = new HomeSetBean();
            homeSetBean.setObjId(BaseCommonUtils.generateUUID());
            homeSetBean.setConstructionWorkSiteId(dto.getConstructionWorkSiteId());
            homeSetBean.setPlayWindowNum(dto.getPlayWindowNum());
            homeSetBean.setDefaultSetting(1);
            homeSetBean.setChannelObjId(channelObjIdStr);
        }

        //先把保存的默认现场和摄像机设置为非默认
        this.lambdaUpdate()
                .eq(HomeSetBean::getDefaultSetting,1)
                .set(HomeSetBean::getDefaultSetting, 0)
                .update();
        return this.saveOrUpdate(homeSetBean);
    }

    @Override
    public HomeSetInfoVO getHomeSetInfo(HomeInfoGetInfoDTO dto) throws GeneralSimpleException {
        HomeSetInfoVO homeSetInfoVO = new HomeSetInfoVO();
        LambdaQueryWrapper<HomeSetBean> wrapper = Wrappers.lambdaQuery();
        if (StringUtils.isNotBlank(dto.getConstructionWorkSiteId())){
            wrapper.eq(HomeSetBean::getConstructionWorkSiteId,dto.getConstructionWorkSiteId());
        }else{
            wrapper.eq(HomeSetBean::getDefaultSetting,1);
        }
        wrapper.orderByDesc(HomeSetBean::getCreateTime);
        List<HomeSetBean> list = this.baseMapper.selectList(wrapper);
        if (CollectionUtils.isNotEmpty(list)){
            HomeSetBean homeSetBean = list.get(0);
            homeSetInfoVO.setConstructionWorkSiteId(homeSetBean.getConstructionWorkSiteId());
            homeSetInfoVO.setPlayWindowNum(homeSetBean.getPlayWindowNum());

            // 校验授权
            constructionWorkSiteService.checkGrantByObjId(dto.getConstructionWorkSiteId());
            
            ConstructionWorkSiteBean constructionWorkSiteBean = constructionWorkSiteService.getById(homeSetInfoVO.getConstructionWorkSiteId());
            if (constructionWorkSiteBean != null){
                homeSetInfoVO.setWorkSiteName(constructionWorkSiteService.getNewSiteName(constructionWorkSiteBean));
                homeSetInfoVO.setIfGrant(constructionWorkSiteBean.getIfGrant());
            }
            if(StringUtils.isNotBlank(homeSetBean.getChannelObjId())){
                List<String> objIdList = Arrays.stream(homeSetBean.getChannelObjId().split(",", -1)).collect(Collectors.toList());
                List<PatrolIntelligentEquipChannel> intelligentEquipChannelList = patrolIntelligentEquipChannelService.lambdaQuery()
                        .in(CollectionUtils.isNotEmpty(objIdList), PatrolIntelligentEquipChannel::getObjId, objIdList)
                        .list();
                if (CollectionUtils.isNotEmpty(intelligentEquipChannelList)) {
                    List<PatrolIntelligentEquipTreeVO> idNameList = Lists.newArrayList();
                    for (PatrolIntelligentEquipChannel c : intelligentEquipChannelList) {
                        PatrolIntelligentEquip patrolIntelligentEquip = patrolIntelligentEquipService.getById(c.getEquipId());
                        if (Objects.isNull(patrolIntelligentEquip)){
                            continue;
                        }
                        PatrolIntelligentEquipTreeVO idName = new PatrolIntelligentEquipTreeVO();
                        idName.setObjId(c.getObjId());
                        idName.setType("04");
                        idName.setChannelNumber(c.getChannelNumber());
                        idName.setEquipChannelNumber(c.getEquipChannelNumber());
                        idName.setBelongEquipId(c.getBelongEquipId());
                        idName.setEquipId(c.getEquipId());
                        idName.setUseMode(patrolIntelligentEquip.getUseMode());
                        idName.setUrlType(c.getUrlType());
                        idName.setIsOnline(patrolIntelligentEquip.getIsOnline());
                        idName.setPtz(patrolIntelligentEquip.getPtz());
                        idName.setNight(patrolIntelligentEquip.getNight());
                        idName.setWiper(patrolIntelligentEquip.getWiper());
                        idName.setChannelCode(c.getChannelCode());
                        idName.setChannelCodeNvr(c.getChannelCodeNvr());
                        idNameList.add(idName);
                    }
                    homeSetInfoVO.setChannelVOList(idNameList);
                }
            }
        }
        return homeSetInfoVO;
    }


    @Override
    public IPage<PatrolIntelligentEquipChannelNvrVO> findNoHomeSetChannelListPage(PatrolIntelligentEquipChannelHomeDTO dto) throws GeneralSimpleException {
        Page<PatrolIntelligentEquipChannel> page = new Page<>(dto.getPage(), dto.getSize());
        List<ConstructionWorkSiteBean> constructionWorkSiteBeanList = constructionWorkSiteService.lambdaQuery()
                .eq(StringUtils.isNotBlank(dto.getConstructionWorkSiteId()), ConstructionWorkSiteBean::getObjId, dto.getConstructionWorkSiteId())
                .orderByAsc(ConstructionWorkSiteBean::getCreateTime).list();
        if (CollectionUtils.isNotEmpty(constructionWorkSiteBeanList)) {
            List<String> workSiteObjIdList = com.google.common.collect.Lists.newArrayList();
            constructionWorkSiteBeanList.stream().forEach(
                    constructionWorkSiteBean -> {
                        workSiteObjIdList.add(constructionWorkSiteBean.getObjId());
                    }
            );
            //查询首页已经展示的施工现场的摄像机信息
            List<HomeSetBean> homeSetBeanList = this.lambdaQuery()
                    .in(HomeSetBean::getConstructionWorkSiteId, workSiteObjIdList).list();
            if (CollectionUtils.isNotEmpty(homeSetBeanList)) {
                List<String> homeSetChannelIds = homeSetBeanList.stream().map(HomeSetBean::getChannelObjId).collect(Collectors.toList());
                List<String> channelIdList = Lists.newArrayList();
                homeSetChannelIds.forEach(str -> {
                    if(StringUtils.isNotBlank(str)){
                        channelIdList.addAll(Arrays.asList(str.split(",", -1)));
                    }
                });
                
                return patrolIntelligentEquipChannelService.findNoHomeSetChannelListPage(page, dto.getSearchName(), workSiteObjIdList, channelIdList);
            }
        }
        return null;
    }
}
